package com.ihd.ihardware.common.widget;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import cn.wowjoy.commonlibrary.utils.DensityUtil;


public class BubbleProgressView extends View {
    private Paint mPaintProgress;
    private PathMeasure mPathMeasure;
    private Path mPathSrc, mPathDst;
    private int mColorProgressBg;//进度条的背景颜色
    private int mColorProgress;//进度条的进度颜色
    private float mProgressHeight = DensityUtil.dip2px(4);
    private float mProgress = 0;//进度条的进度

    public BubbleProgressView(Context context) {
        this(context, null);
    }

    public BubbleProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BubbleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaintProgress = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
        mPaintProgress.setStyle(Paint.Style.STROKE);
        mPaintProgress.setStrokeWidth(mProgressHeight);

        mPathSrc = new Path();
        mPathDst = new Path();
        mPathMeasure = new PathMeasure();

        mColorProgressBg = 0xFF292B3D;
        mColorProgress = 0xFF00D1A4;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mPathSrc.moveTo(30, h - mProgressHeight * 2);
        mPathSrc.lineTo(w - 30, h - mProgressHeight * 2);//进度条位置在控件整体底部，且距离控件左边和右边各20像素
        mPathMeasure.setPath(mPathSrc, false);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawProgress(canvas);
    }

    private void drawProgress(Canvas canvas) {
        mPathDst.reset();
        mPaintProgress.setColor(mColorProgressBg);
        canvas.drawPath(mPathSrc, mPaintProgress);//绘制进度背景（灰色部分）
        float stop = mPathMeasure.getLength() * mProgress;//计算进度条的进度
        mPathMeasure.getSegment(0, stop, mPathDst, true);//得到与进度对应的路径
        mPaintProgress.setColor(mColorProgress);
        canvas.drawPath(mPathDst, mPaintProgress);//绘制进度
    }

    /**
     * 设置进度
     *
     * @param progress
     */
    public void setProgress(float progress) {
        mProgress = progress;
        invalidate();//设置完进度进行重绘
    }

    /**
     * 设置动画进度
     */
    public void setProgressWithAnim(float progress) {
        ObjectAnimator.ofFloat(this, "progress", 0, progress).setDuration(2000).start();
    }
}